//
//  FPMeViewController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/15.
//

#import "FPMeViewController.h"
#import "FPMeHeaderView.h"
#import "FPSettingController.h"
#import "FPManualController.h"
#import <CommonCrypto/CommonCryptor.h>
#import "FPFeedBackController.h"
#import "FPMyInfoController.h"
#import "FPInreviewController.h"
#import "FPBorrowingController.h"
#import "FPRepaymentController.h"
#import "FPLoanDetailController.h"
#import "FPAuthenticationController.h"
#import "FPLoanDetailModel.h"
#import "FPProtocolListController.h"
#import "FPCustomerModel.h"
#import "FPMeMainCell.h"
#import "FPSettingCell.h"
#import "FPMeProfileController.h"
#import "FPNotificationController.h"
#import "FPToRepayDetailController.h"
#import "FPBankCardManageController.h"
#import "FPNoDataController.h"
#import "FPLoginController.h"
#import "FPHelpCenterController.h"
#import "FPMeProfileEditController.h"

#import <IQKeyboardManager/IQKeyboardManager.h>

@interface FPMeViewController () <UITableViewDelegate , UITableViewDataSource , UITextFieldDelegate>

@property (nonatomic,strong) FPMeHeaderView *headerView;

@property (nonatomic , strong) FPLoanDetailListModel *loanModel;

@property (nonatomic , strong) NSArray *imageSource;
@property (nonatomic , strong) NSArray *titleSource;

@end

@implementation FPMeViewController

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [UIViewController popGestureClose:self];
    
    // 确保TabBar可见 - 设置hidesBottomBarWhenPushed为NO
    self.hidesBottomBarWhenPushed = NO;
    
    // 强制刷新TabBar显示
    if (self.tabBarController && self.tabBarController.tabBar) {
        // 确保TabBar不是隐藏状态
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.alpha = 1.0;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [UIViewController popGestureOpen:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 确保我的页面显示TabBar
    self.hidesBottomBarWhenPushed = NO;
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    // 退出登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFaild) name:LogoutNotification object:nil];
    // 登录失效
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFaild) name:UserTokenInvalidNotification object:nil];
    // 登录成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:LoginSuccessNotification object:nil];
    
//    self.imageSource = @[@"icon_me_cell_v2_1" , @"icon_me_cell_v2_2" , @"icon_me_cell_v2_3"];
//    self.titleSource = @[@"防诈手册" , @"意见反馈" , @"帮助中心"];
    self.imageSource = @[@"icon_me_cell_v2_1" , @"icon_me_cell_v2_2"];
    self.titleSource = @[@"防诈手册" , @"意见反馈"];
}

- (void)initUI {

//    self.controllerType = TypeOfHomeOrProfileProfile;
//    
//    self.showLoginWindow = NO;
//    self.hideTabBar = NO;
    [self setTitle:@"" style:(XYCustomNavigationStyleClear) hiddenBackBtn:YES];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = UIColor.clearColor;
    self.tableView.frame = CGRectMake(0.f, 0, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.tabBarFullHeight);
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPMeHeaderView.class) owner:nil options:nil].lastObject;
    self.tableView.tableHeaderView = self.headerView;
    self.headerView.backgroundColor = UIColor.clearColor;
    self.headerView.headToTop.constant = UIDevice.safeDistanceTop + 45.f;
//    self.headerView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, 410.f);
    self.headerView.height += UIDevice.safeDistanceTop;
    
    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, SCREEN_WIDTH, 20.f)];
    footer.backgroundColor = UIColor.clearColor;
    self.tableView.tableFooterView = footer;
    
    self.tableView.rowHeight = 50.f;
    
    [self.headerView.toLoginView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loginAction)]];
    [self.headerView.settingImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toSettingAction)]];
    
    [self.headerView.view1 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(footerAction1)]];
    [self.headerView.view2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(footerAction2)]];
    [self.headerView.view3 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(footerAction3)]];
    
    [self.headerView.infoView3 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoAction1)]];
    [self.headerView.infoView3 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoAction2)]];
    [self.headerView.infoView3 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoAction3)]];
    
    // 还款记录
    [self.headerView.repayRecordListLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(repayRecordListAction)]];
    
    [self refreshData];
    FPCustomRefreshHeader *refreshHeader = [FPCustomRefreshHeader headerWithRefreshingBlock:^{
        
//        [self stopTimer];
        
        [self refreshData];
    }];
    [refreshHeader setActivityColor:UIColor.grayColor];
    refreshHeader.statusLabColor = UIColor.grayColor;
    self.tableView.mj_header = refreshHeader;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
#pragma mark - 去还款 btn
    [self.headerView.repayBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
       
#warning ~~ 去还款 在v2版本 是一个单独的控制器 FPToRepayDetailController
//        if (self.loanModel.loanId.length) {
         
            FPToRepayDetailController *vc = [[FPToRepayDetailController alloc] init];
//            vc.loanID = self.loanModel.loanId;
            [self.navigationController pushViewController:vc animated:YES];
//        }
    }];
    
    [self customerList];
//    NSLog(@"%@",FPUserInfoModel.sharedUserInfo.ID);
    [self refreshUINotLogin];
}

#pragma mark - 获取客服列表(电话)
- (void)customerList {
    
    [MBManager showLoading];
    [FPCustomerModel getCustomersSuccess:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            for (FPCustomerModel *model in list) {
                
                if ([model.ID isEqualToString:@"3"]) {
                    
                    FPUserInfoModel *m = FPUserInfoModel.sharedUserInfo;
                    m.customerContact = model.contactValue;
                    [FPUserInfoModel saveUserInfo:m];
                }
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
//    if (self.showLoginWindow) {
//        
//        [self loginAction];
//    }
}


- (void)loginAction {
    
    FPLoginController *vc = [[FPLoginController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 去设置
- (void)toSettingAction {
    
    if ([self userIsLogin]) {
     
        FPSettingController *vc = [[FPSettingController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark - 未登录
- (void)loginFaild {
    
    self.headerView.lab1.text = @"登录/注册";
    self.headerView.lab2.text = @"登录可享更多精彩";
    self.headerView.toLoginView.userInteractionEnabled = YES;
    
    [self refreshUINotLogin];
}



#pragma mark - 登录成功 刷新
- (void)refreshData {
    
    [self customerList];
    
//    [MBManager showLoading];
    [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
//        [MBManager hideLoading];
        
        if (model.phone.length > 1) {
            
            self.headerView.lab1.text = [model.phone stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
            self.headerView.lab2.text = @"欢迎来到众鑫花";
            self.headerView.toLoginView.userInteractionEnabled = NO;
            
            [self getCurrenMonthRepayInfo];
        }
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - 获取当月待还计划
- (void)getCurrenMonthRepayInfo {

    [FPLoanDetailListModel getUserCurrenMonthLoan:@{} success:^(NSInteger code, NSString * _Nonnull message, FPLoanDetailListModel * _Nonnull model) {
        
        self.loanModel = model;
        [self refreshUI];
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
    }];
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, SCREEN_WIDTH, 50.f)];
    view.backgroundColor = UIColor.whiteColor;
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16.f + 12.f, 12.f, 200.f, 26.f)];
    lab.text = @"我的工具";
    lab.font = [UIFont systemFontOfSize:16.f weight:(UIFontWeightSemibold)];
    lab.textColor = [UIColor hexColor:@"#3A3A3A"];
    [view addSubview:lab];
    
    [UIView setCornerForView:view withRadius:8.f bounds:CGRectMake(16.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerTopLeft | UIRectCornerTopRight)];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 50.f;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.imageSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPSettingCell *cell;
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPSettingCell.class) owner:nil options:nil].lastObject;
    }
    
    cell.subTitleLab.hidden = YES;
    cell.mainImgView.image = IMG(self.imageSource[indexPath.row]);
    cell.titleLab.text = self.titleSource[indexPath.row];
    
    if (indexPath.row == self.imageSource.count - 1) {
        
        [UIView setCornerForView:cell.backView withRadius:8.f bounds:CGRectMake(0.f, 0.f, SCREEN_WIDTH - 32.f, 50.f) corners:(UIRectCornerBottomLeft | UIRectCornerBottomRight)];
        cell.lineView.hidden = YES;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 防诈手册
    if (indexPath.row == 0) {
        
        FPManualController *vc = [[FPManualController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    // 意见反馈
    else if (indexPath.row == 1) {
        
        if ([self userIsLogin]) {
         
            [self feedbackAction];
        }
    }
    // 帮助中心
    else if (indexPath.row == 2) {
        
        if ([self userIsLogin]) {
         
            [self helpCenterAction];
        }
    }
}


#pragma mark - v2 借款记录
- (void)repayRecordListAction {
    
    if ([self userIsLogin]) {
        
//        FPBorrowingController *vc = [[FPBorrowingController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
        FPRepaymentController *vc = [[FPRepaymentController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark - footer 3事件
#pragma mark - 实名认证
- (void)footerAction1 {
    
    if ([self userIsLogin]) {
     
        FPUserInfoModel *userInfo = FPUserInfoModel.sharedUserInfo;
        
        if (userInfo.idcardNumber.length) {
         
            FPMyInfoController *vc = [[FPMyInfoController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else {
            
            FPAuthenticationController *vc = [[FPAuthenticationController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

#pragma mark - 个人信息
- (void)footerAction2 {
    
    if ([self userIsLogin]) {
        
        [MBManager showLoading];
        [FPUserInfoModel checkUserProfileInfoSuccess:^(NSInteger code, NSString * _Nonnull message , FPUserInfoModel *userInfoModel) {
            [MBManager hideLoading];
            
            NSInteger statusCode = userInfoModel.status.integerValue;
            
//            入资状态判断（0未实名，1已实名，2留资1完成，3留资2完成）
            if (statusCode == 0) {
                
                FPAuthenticationController *vc = [[FPAuthenticationController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else {
                
                FPMeProfileEditController *vc = [[FPMeProfileEditController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        } failure:^(NSError * _Nonnull error) {
            [self showError:error];
        }];
        
        
    }
}

#pragma mark - 银行卡
- (void)footerAction3 {
    
    if ([self userIsLogin]) {
     
        FPBankCardManageController *vc = [[FPBankCardManageController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}



#pragma mark - 登录校验
- (BOOL)userIsLogin {

    BOOL ret = YES;
    
    if (FPUserInfoModel.sharedUserInfo.phone.length < 1) {
        
        ret = NO;
        FPLoginController *vc = [[FPLoginController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    return ret;
}

- (void)refreshUI {
    
    if (FPUserModel.globalToken.length > 0) {
        
        // 有当月待还
        if (self.loanModel.totalAmountToPay.floatValue > 0.f) {
            
            self.headerView.repayAmountLab.text = self.loanModel.totalAmountToPay;
            self.headerView.repayTimeTipLab.text = [NSString stringWithFormat:@"最近还款日：%@", [FPBorrowingAndRepaymentModel timeOfParam:self.loanModel.repaymentDate]];
            
            // 有借款 有还款 UI
            [self refreshUIBillWithRepay];

            //        有借款 未还款 UI
            //        [self refreshUIBillNoRepay];

            //        有借款 已还完 UI
            //        [self refreshUIBillClear];
        }
        else {
            
            [self refreshUIBillWithRepay];
        }
    }
    else {
        
        // 未登录UI
        [self refreshUINotLogin];
    }
}

#pragma mark - 未登录UI
- (void)refreshUINotLogin {
    
    self.headerView.infoLab1.text = @"-";
    self.headerView.infoLab2.text = @"-";
    self.headerView.infoLab3.text = @"-";
    self.headerView.repayRecordListLab.hidden = YES;
    self.headerView.repayTipLab.text = @"借款账单";
    self.headerView.repayAmountLab.text = @"-";
    self.headerView.repayTimeTipLab.text = @"暂无借贷";
    self.headerView.repayBtn.hidden = YES;
    self.headerView.labToRight.constant = 12.f;
}

//#pragma mark - 有借款 未还款 UI
//- (void)refreshUIBillNoRepay {
//    
////    self.headerView.repayBtn.hidden = NO;
//    self.headerView.repayBtn.hidden = YES;
//    self.headerView.repayRecordListLab.hidden = YES;
//    self.headerView.repayTipLab.text = @"本月待还";
//    self.headerView.repayAmountLab.text = @"0";
//    self.headerView.repayTimeTipLab.text = @"最近还款日: 无需还款";
//}

#pragma mark - 有借款 有还款 UI
- (void)refreshUIBillWithRepay {
    
//    self.headerView.repayBtn.hidden = NO;
    self.headerView.repayBtn.hidden = NO;
    self.headerView.labToRight.constant = 92.f;
    self.headerView.repayRecordListLab.hidden = NO;
    self.headerView.repayTipLab.text = @"借款账单";
    self.headerView.repayAmountLab.text = @"-";
    self.headerView.repayTimeTipLab.text = @"";
}

#pragma mark - 有借款 已还完 UI
- (void)refreshUIBillClear {
    
    self.headerView.repayBtn.hidden = NO;
    self.headerView.labToRight.constant = 92.f;
    self.headerView.labToRight.constant = 12.f;
    self.headerView.repayRecordListLab.hidden = NO;
    self.headerView.repayTipLab.text = @"本月待还";
    self.headerView.repayAmountLab.text = @"0";
    self.headerView.repayTimeTipLab.text = @"最近还款日: 无需还款";
}


#pragma mark - 意见反馈
- (void)feedbackAction {
    
    if ([self userIsLogin]) {
     
        FPFeedBackController *vc = [[FPFeedBackController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark - 帮助中心
- (void)helpCenterAction {
    
    FPHelpCenterController *vc = [[FPHelpCenterController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 联系我们
- (void)contactUsAction {
    
    if ([self userIsLogin]) {
        
        NSString *phoneNumber = FPUserInfoModel.sharedUserInfo.customerContact;
        
        LXAlertView *alert = [[LXAlertView alloc] initContactUsServicePhone:phoneNumber alertAlertResult:^(NSInteger index) {
           
            if (index == 1) {
                
    //            [self showText:@"1"];
            }
            else if (index == 2) {
                
                NSString *telURLString = [NSString stringWithFormat:@"tel://%@", phoneNumber];
                NSURL *telURL = [NSURL URLWithString:telURLString];
                
                // 确保 URL 可以被打开
                if ([[UIApplication sharedApplication] canOpenURL:telURL]) {
                    
                    [[UIApplication sharedApplication] openURL:telURL options:@{} completionHandler:nil];
                }
                else {
                    NSLog(@"无法打开电话拨号界面");
                }
            }
        }];

        [alert showLXAlertView];
    }
}


#pragma mark - 信用分
- (void)infoAction1 {
    
//    if ([self userIsLogin]) {
//    }
}

#pragma mark - 可借额度
- (void)infoAction2 {
    
//    if ([self userIsLogin]) {
//    }
}

#pragma mark - 通知中心
- (void)infoAction3 {
    
    if ([self userIsLogin]) {
        
        FPNotificationController *vc = [[FPNotificationController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}






@end
